import axios, { AxiosInstance } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import qs from "qs";

const service: AxiosInstance = axios.create({
    // baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
    // baseURL: "http://localhost:3001/api/",
    baseURL: "http://47.100.62.134:3002/api/",
    timeout: 20 * 1000, // request timeout
    headers: {
        "Content-Type": "application/json",
    },
    paramsSerializer: {
        serialize: (params) => {
            return qs.stringify(params, { arrayFormat: "repeat" });
        },
    },
});
// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么
        const token = localStorage.getItem("ACCESS_TOKEN");
        if (token) {
            config.headers["Authorization"] = "Bear " + token;
        }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);
// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        const res = response.data;
        if (res.code !== 200) {
            ElMessage({
                message: res.message || "Error",
                type: "error",
            });
            return Promise.reject(new Error(res.message || "Error"));
        } else {
            return res;
        }
    },
    (error) => {
        // 对响应错误做点什么
        ElMessage({
            message: error.message,
            type: "error",
        });
        return Promise.reject(error);
    }
);
export default service;
